<template>
  <div class="card fourAspect">
    <div class="table-container">
      <div class="top-search">
        <el-form :inline="true" :model="formData" class="demo-form-inline">
          <el-form-item class="left">
            <el-tree-select
              style="width: 100%"
              check-strictly
              v-model="formData.Fonds_ID"
              @change="getClassData"
              node-key="Fonds_ID"
              :props="{ label: 'Fonds_Name', children: 'children' }"
              :data="FatherData"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item class="left">
            <el-select v-model="formData.FM_ID" placeholder="请选择归档方式" @change="getTableData">
              <el-option v-for="item in classData" :key="item.FM_ID" :label="item.FM_OCName" :value="item.FM_ID" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="formData.FM_TB_ID" placeholder="请选择数据表" @change="getTableNameId">
              <el-option v-for="item in tableNameData" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <div class="btns">
            <!-- <el-button type="primary" @click="search">查询</el-button> -->
            <el-button type="success" @click="addSingleData" :icon="Plus">新建检测项</el-button>
            <el-button type="primary" @click="addDataList">一键导入</el-button>
            <!-- <el-button type="primary" @click="update">修改</el-button> -->
            <el-button type="warning" @click="delAll">一键删除</el-button>
            <el-button type="danger" @click="delPart">批量删除</el-button>
          </div>
        </el-form>
      </div>
      <stable
        :columns="tableSetting.columns"
        :data="tableSetting.data"
        :toolbarConfigVisible="true"
        @selectionChange="selectChange"
      ></stable>
    </div>

    <vxe-pager
      v-model:currentPage="page.currentPage"
      v-model:pageSize="page.pageSize"
      :pageSizes="[100, 500, 1000, 5000, 10000, 50000]"
      :total="page.total"
      @page-change="pageChange"
    >
    </vxe-pager>

    <!-- 编辑弹框 -->
    <el-dialog v-model="dialogFormVisible" :title="modalType === 1 ? '新增' : '编辑'" width="850" draggable>
      <el-form :model="modelFormData" ref="ruleFormRef" :rules="rules">
        <!-- 检测阶段和四性 -->
        <div class="edit-item">
          <el-form-item label="检测阶段" prop="FourAspect_stages">
            <el-select v-model="modelFormData.FourAspect_stages" placeholder="请选择阶段" @change="changeFourAspectStages">
              <el-option v-for="item in FourAspectStagesList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="检测四性" prop="FourAspect_Class">
            <el-select v-model="modelFormData.FourAspect_Class" placeholder="请选择四性" @change="changeFourAspectClass">
              <el-option v-for="item in FourAspectClassList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 检测小类和编号 -->
        <div class="edit-item">
          <el-form-item label="检测小类" prop="Small_Class">
            <el-select v-model="modelFormData.Small_Class" placeholder="请选择小类" @change="changeSmallClass">
              <el-option v-for="item in SmallClassList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="检测编号" prop="code">
            <el-select v-model="modelFormData.code" placeholder="请选择编号" @change="changeCode">
              <el-option v-for="item in codeList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 检测项目和目的 -->
        <div class="edit-item">
          <el-form-item label="检测项目" prop="Verification_Item">
            <el-select v-model="modelFormData.Verification_Item" placeholder="请选择项目">
              <el-option v-for="item in VerificationItemList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="检测目的" prop="Verification_Purpose">
            <el-select v-model="modelFormData.Verification_Purpose" placeholder="请选择目的">
              <el-option v-for="item in VerificationPurposeList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 检测对象和启用、人工选项 -->
        <div class="edit-item">
          <el-form-item label="检测对象" prop="Verification_Target">
            <el-select v-model="modelFormData.Verification_Target" placeholder="请选择对象">
              <el-option v-for="item in VerificationTargetList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <div class="check-groups">
            <el-form-item label="启用" prop="enable">
              <el-checkbox v-model="modelFormData.enable" />
            </el-form-item>

            <el-form-item label="人工" prop="Is_Manual_Processing">
              <el-checkbox v-model="modelFormData.Is_Manual_Processing" />
            </el-form-item>

            <el-form-item label="演示">
              <el-checkbox v-model="modelFormData.DefValue" />
            </el-form-item>
          </div>
        </div>

        <!-- 条件项、操作符、匹配项 -->
        <div class="options">
          <el-form-item label="条件项" label-width="78px" prop="Condition_Item">
            <el-input v-model="modelFormData.Condition_Item" placeholder="条件项" />
          </el-form-item>

          <el-form-item label="操作符" label-width="78px" prop="Operator">
            <el-input v-model="modelFormData.Operator" placeholder="操作符" />
          </el-form-item>

          <el-form-item label="匹配项" label-width="78px" prop="Match_Item">
            <el-input v-model="modelFormData.Match_Item" placeholder="匹配项" />
          </el-form-item>
        </div>

        <!-- 检测依据和方法 -->
        <el-form-item label="检测依据和方法" prop="Verification_Basis_Method">
          <el-input
            type="textarea"
            v-model="modelFormData.Verification_Basis_Method"
            :rows="3"
            placeholder="请输入检测依据和方法"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted, watch } from "vue";
import type { FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { transTree, fileToBase64 } from "@/utils/util";
import { getCurTime } from "@/utils/formatter";
// @ts-expect-error
import fourAspectDataList from "@/assets/json/fourAspectDataList.js";
const { proxy } = useCurrentInstance();

interface PageChangeParams {
  pageSize: number;
  currentPage: number;
}

// 搜索表单
const formData = reactive({
  Fonds_ID: "",
  FM_ID: "",
  FM_TB_ID: ""
});

// 弹框表单绑定字段
const modelFormData = ref({
  faC_ID: "",
  table_id: "",
  FourAspect_stages: "",
  FourAspect_Class: "",
  Small_Class: "",
  code: "",
  Verification_Item: "",
  Verification_Purpose: "",
  Verification_Target: "",
  Verification_Basis_Method: "",
  enable: true,
  Is_Manual_Processing: "",
  Condition_Item: "",
  Operator: "",
  Match_Item: "",
  create_DateTime: "",
  DefValue: false
});

// 树结构全宗
const FatherData = ref<any[]>([]);

// 归档数据
const classData = ref();

// 表数据
const tableNameData = ref();

// 全宗数据
const FondsData = ref();

// 复选框选中的行id
const delFAC_IDs = ref<any>([]);

// 编辑或新增弹框
const dialogFormVisible = ref<boolean>(false);

// 弹框类型 1：新增 2：编辑
const modalType = ref<number>(1);

const ruleFormRef = ref(); // 表单实例

const tableSetting = reactive({
  columns: [
    { type: "checkbox", width: 55 },
    { field: "order", title: "序号", width: 70, sortable: true },
    { field: "FourAspect_stages", title: "阶段", sortable: true },
    { field: "FourAspect_Class", title: "四性", sortable: true },
    { field: "Small_Class", title: "小类", sortable: true },
    { field: "code", title: "编号", sortable: true },
    { field: "Verification_Item", title: "检测项目", sortable: true },
    { field: "Verification_Purpose", title: "检测目的", sortable: true },
    { field: "Verification_Target", title: "检测对象", sortable: true },
    { field: "Verification_Basis_Method", title: "检测依据和方法", sortable: true },
    {
      field: "enable",
      title: "是否启用",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return row.enable ? "是" : "否";
        }
      }
    },
    { field: "table_id", title: "被配制业务表的ID", sortable: true },
    { field: "Create_DateTime", title: "创建日期", sortable: true },
    {
      field: "Is_Manual_Processing",
      title: "是否人工",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return row.Is_Manual_Processing ? "是" : "否";
        }
      }
    },
    {
      field: "DefValue",
      title: "演示",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return row.DefValue ? "是" : "否";
        }
      }
    },
    { field: "Condition_Item", title: "条件项", sortable: true },
    { field: "Operator", title: "操作符", sortable: true },
    { field: "Match_Item", title: "匹配项", sortable: true },
    {
      title: "操作",
      width: 180,
      align: "center",
      slots: {
        default: ({ row }: any) => {
          return (
            <div>
              <el-button type="warning" link onClick={() => enableHandle(row)}>
                {row.enable ? "禁用" : "启用"}
              </el-button>
              <el-button type="primary" link onClick={() => edit(row)}>
                编辑
              </el-button>
              <el-button type="danger" link onClick={() => del(row)}>
                删除
              </el-button>
            </div>
          );
        }
      }
    }
  ],
  data: [],
  selectData: [] // 多选数据
});

// 校验规则
const rules = reactive({
  FourAspect_stages: [{ required: true, message: "此项为必填项", trigger: "change" }],
  FourAspect_Class: [{ required: true, message: "此项为必填项", trigger: "change" }],
  Small_Class: [{ required: true, message: "此项为必填项", trigger: "change" }],
  code: [{ required: true, message: "此项为必填项", trigger: "change" }],
  Verification_Item: [{ required: true, message: "此项为必填项", trigger: "change" }],
  Verification_Purpose: [{ required: true, message: "此项为必填项", trigger: "change" }],
  Verification_Target: [{ required: true, message: "此项为必填项", trigger: "change" }]
});

// 编辑弹框 ***** 开始

const FourAspectStagesList = new Set(fourAspectDataList.map((item: any) => item.FourAspect_stages)); // 检测阶段
let FourAspectClassList = ref<any>([]); // 检测四性
let SmallClassList = ref<any>([]); // 检测小类
let codeList = ref<any>([]); // 检测编号
let VerificationItemList = ref([]); // 检测项目
let VerificationPurposeList = ref([]); // 检测目的
let VerificationTargetList = ref([]); // 检测对象

// 检测阶段改变-其他各筛选框数据初始化
const changeFourAspectStages = (val: any) => {
  modelFormData.value = {
    ...modelFormData.value,
    FourAspect_Class: "",
    Small_Class: "",
    code: "",
    Verification_Item: "",
    Verification_Purpose: "",
    Verification_Target: ""
  };
  FourAspectClassList.value = []; // 检测四性
  SmallClassList.value = []; // 检测小类
  codeList.value = []; // 检测编号
  VerificationItemList.value = []; // 检测项目
  VerificationPurposeList.value = []; // 检测目的
  VerificationTargetList.value = []; // 检测对象
  getFourAspectClassList();
};
// 获取检测四性列表
const getFourAspectClassList = () => {
  FourAspectClassList.value = new Set(
    fourAspectDataList
      .filter((item: any) => item.FourAspect_stages === modelFormData.value.FourAspect_stages)
      .map((item: any) => item.FourAspect_Class)
  );
};
// 获取检测四性改变-其他各筛选框数据初始化
const changeFourAspectClass = (val: any) => {
  modelFormData.value = {
    ...modelFormData.value,
    Small_Class: "",
    code: "",
    Verification_Item: "",
    Verification_Purpose: "",
    Verification_Target: ""
  };
  SmallClassList.value = []; // 检测小类
  codeList.value = []; // 检测编号
  VerificationItemList.value = []; // 检测项目
  VerificationPurposeList.value = []; // 检测目的
  VerificationTargetList.value = []; // 检测对象
  getSmallClassList(); //获取检测小类列表
};

// 获取检测小类列表
const getSmallClassList = () => {
  SmallClassList.value = new Set(
    fourAspectDataList
      .filter((item: any) => {
        const { FourAspect_stages, FourAspect_Class } = modelFormData.value;
        if (item.FourAspect_stages === FourAspect_stages && item.FourAspect_Class === FourAspect_Class) {
          return item;
        }
      })
      .map((item: any) => item.Small_Class)
  );
};

// 获取检测四性改变-其他各筛选框数据初始化
const changeSmallClass = (val: any) => {
  modelFormData.value = {
    ...modelFormData.value,
    code: "",
    Verification_Item: "",
    Verification_Purpose: "",
    Verification_Target: ""
  };
  codeList.value = []; // 检测编号
  VerificationItemList.value = []; // 检测项目
  VerificationPurposeList.value = []; // 检测目的
  VerificationTargetList.value = []; // 检测对象
  getCodeList(); //获取检测编号列表
};

// 获取检测编号列表
const getCodeList = () => {
  const newDataList = fourAspectDataList.filter((item: any) => {
    const { Small_Class } = modelFormData.value;
    if (item.Small_Class === Small_Class) {
      return item;
    }
  });
  codeList.value = new Set(newDataList.map((item: any) => item.code));
};

// 检测编号改变-其他各筛选框数据初始化
const changeCode = (val: any) => {
  modelFormData.value = {
    ...modelFormData.value,
    Verification_Item: "",
    Verification_Purpose: "",
    Verification_Target: ""
  };
  VerificationItemList.value = []; // 检测项目
  VerificationPurposeList.value = []; // 检测目的
  VerificationTargetList.value = []; // 检测对象
  getOtherList(); //获取其他列表
};

// 获取其他列表
const getOtherList = () => {
  const newDataList = fourAspectDataList.filter((item: any) => {
    const { code } = modelFormData.value;
    if (item.code === code) return item;
  });
  VerificationItemList.value = newDataList.map((item: any) => item.Verification_Item);
  VerificationPurposeList.value = newDataList.map((item: any) => item.Verification_Purpose);
  VerificationTargetList.value = newDataList.map((item: any) => item.Verification_Target);
  modelFormData.value = {
    ...modelFormData.value,
    Verification_Item: VerificationItemList.value[0],
    Verification_Purpose: VerificationPurposeList.value[0],
    Verification_Target: VerificationTargetList.value[0]
  };
};

// 编辑弹框 ***** 结束

// 分页配置
const page = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 20
});

const edit = (row: any) => {
  modelFormData.value = row;
  modalType.value = 2; // 标题显示新增
  dialogFormVisible.value = true;
  getFourAspectClassList();
  getSmallClassList();
  getCodeList();
  getOtherList();
};

// 多选
const selectChange = (val: any) => {
  tableSetting.selectData = val;
  delFAC_IDs.value = [];
  val.forEach((item: any) => {
    delFAC_IDs.value.push(item.FAC_ID);
  });
};

// 批量删除
const delPart = () => {
  if (!tableSetting.selectData.length) {
    proxy.$message.warning("请选择需要删除的数据!");
    return;
  }
  proxy.$messageBox
    .confirm("确定删除所选检测配置项？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      commonDel(delFAC_IDs.value);
    });
};

// 启用禁用操作
const enableHandle = (row: any) => {
  proxy.$messageBox
    .confirm(`确定${row.enable ? "禁用" : "启用"}该检测配置项？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      modelFormData.value = row;
      modelFormData.value.enable = !row.enable;
      update();
    });
};

// 一键删除
const delAll = () => {
  if (!formData.FM_TB_ID) {
    proxy.$message.warning("请选择数据表!");
    return;
  }
  proxy.$messageBox
    .confirm("确定删除所有检测配置项？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios
        .post("Master_Base_FourAspect_Conf/DeleteByMultipleConditions", [
          {
            fieldName: "table_id",
            conditionalType: 0,
            fieldValue: formData.FM_TB_ID
          }
        ])
        .then((res: any) => {
          console.log("删除所有测试---", res);
          if (res.Mark) {
            proxy.$message.success("删除成功！");
            search();
          }
        });
    });
};

// 单项删除
const del = (row: any) => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      commonDel([row?.FAC_ID]);
    });
};

const commonDel = (ids: any[]) => {
  proxy.$vueAxios.post("Master_Base_FourAspect_Conf/Delete", ids).then((res: any) => {
    console.log("单项删除测试---", res);
    if (res.Mark) {
      proxy.$message.success("删除成功！");
      search();
    }
  });
};

// 提交修改
const submitHandle = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid: any) => {
    if (valid) {
      if (modalType.value === 1) {
        addSingleConf();
      } else {
        update();
      }
    } else {
      proxy.$message.error("表单校验失败!");
      return false;
    }
  });
};

// 添加单个检测项配置
const addSingleConf = async () => {
  modelFormData.value.faC_ID = proxy.$global.createID();
  modelFormData.value.table_id = formData.FM_TB_ID;
  modelFormData.value.create_DateTime = getCurTime();
  const result = await proxy.$vueAxios.get("MasterBaseFourAspectConf/GetMaxOrder", {
    table_id: formData.FM_TB_ID
  });
  proxy.$vueAxios
    .post("Master_Base_FourAspect_Conf", {
      ...modelFormData.value,
      order: result.Count + 1
    })
    .then((res: any) => {
      if (res.Mark) {
        dialogFormVisible.value = false;
        proxy.$message.success("新增成功！");
        search();
      }
    });
};

// 修改
const update = () => {
  proxy.$vueAxios
    .put("Master_Base_FourAspect_Conf", {
      ...modelFormData.value
    })
    .then((res: any) => {
      console.log("修改测试---", res);
      if (res.Mark) {
        dialogFormVisible.value = false; // 更新成功之后关闭弹窗
        proxy.$message.success("更新成功！");
        search();
      }
    });
};

// 分页调用
const pageChange = ({ pageSize, currentPage }: PageChangeParams) => {
  page.currentPage = currentPage;
  page.pageSize = pageSize;
  search();
};

const getTableNameId = () => {
  if (!formData.FM_TB_ID) {
    proxy.$message.warning("请选择数据表!");
    return;
  }
  search();
};

// 查询检测配置数据
const search = () => {
  proxy.$vueAxios
    .post("Master_Base_FourAspect_Conf/GetConditional", {
      pageIndex: page.currentPage,
      pageSize: page.pageSize,
      order: "table_id asc",
      dtoList: [
        {
          fieldName: "table_id",
          fieldValue: formData.FM_TB_ID,
          conditionalType: 0
        }
      ]
    })
    .then((res: any) => {
      console.log("查询测试---", res);
      if (res.Mark) {
        tableSetting.data = res.List;
        page.total = res.Count;
      }
    });
};

// 添加单条检测配置项
const addSingleData = () => {
  if (!formData.FM_TB_ID) {
    proxy.$message.warning("请选择数据表!");
    return;
  }
  modelFormData.value = {
    // 恢复初始状态值
    faC_ID: "",
    table_id: "",
    FourAspect_stages: "",
    FourAspect_Class: "",
    Small_Class: "",
    code: "",
    Verification_Item: "",
    Verification_Purpose: "",
    Verification_Target: "",
    Verification_Basis_Method: "",
    enable: true,
    Is_Manual_Processing: "",
    Condition_Item: "",
    Operator: "",
    Match_Item: "",
    create_DateTime: "",
    DefValue: false
  };
  modalType.value = 1; // 标题显示新增
  dialogFormVisible.value = true;
};

// 【一键导入】添加检测配置数据
const addDataList = () => {
  if (!formData.FM_TB_ID) {
    proxy.$message.warning("请选择数据表!");
    return;
  }
  // 修饰数据
  fourAspectDataList.forEach((data: any) => {
    data.table_id = formData.FM_TB_ID;
    data.faC_ID = proxy.$global.createID();
  });
  proxy.$vueAxios.post("Master_Base_FourAspect_Conf/AddList", [...fourAspectDataList]).then((res: any) => {
    console.log("测试一下", res);
    if (res.Mark) {
      search();
    }
  });
};

// 获取全宗数据
const getFondsData = () => {
  proxy.$vueAxios.get("Master_Base_Fonds/Get", { order: "Fonds_Order asc" }).then((res: any) => {
    if (res.Mark) {
      FondsData.value = res.List;
      FatherData.value = transTree(FondsData.value, "Fonds_ID", "Fonds_Father");
    }
  });
};

// 获取归档数据
const getClassData = () => {
  proxy.$vueAxios
    .post(
      "Master_Base_Fonds_Class/GetConditional",
      {
        order: "FC_ID asc",
        dtoList: [
          {
            fieldName: "Fonds_ID",
            fieldValue: formData.Fonds_ID,
            conditionalType: 0
          }
        ]
      },
      { noLoading: true }
    )
    .then((res: any) => {
      const fcIds = res.List.map((item: any) => item.FC_ID);
      const result = fcIds.join(",");
      proxy.$vueAxios
        .post(
          "Master_Base_FormModel/GetConditional",
          {
            order: "FM_Index asc",
            dtoList: [
              {
                fieldName: "FC_ID",
                fieldValue: result,
                conditionalType: 6
              }
            ]
          },
          { noLoading: true }
        )
        .then((res2: any) => {
          if (res.Mark) {
            classData.value = res2.List;
          }
        });
    });
};

// 获取数据
const getTableData = () => {
  proxy.$vueAxios
    .post("Master_Base_FormModel_Table/GetConditional", {
      order: "FMT_Type ASC",
      dtoList: [
        {
          fieldName: "FM_ID",
          fieldValue: formData.FM_ID
        }
      ]
    })
    .then((res: any) => {
      console.log("获取数据---", res);
      if (res.Mark) {
        tableNameData.value = []; // 恢复初始状态
        res?.List?.forEach((item: any) => {
          tableNameData.value.push({
            label: `${item.FMT_Name} - ${item.FMT_TableName}`,
            value: item.FMT_ID
          });
        });
      }
    });
};

onMounted(() => {
  getFondsData();
});
</script>

<style lang="scss" scoped>
.fourAspect {
  height: 100%;
  .top-search {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 9;
    display: flex;
    align-items: center;
    .el-form {
      display: flex;
      .el-form-item {
        margin-bottom: 0;
        &:last-child {
          width: 315px;
        }
      }
    }
    .left {
      margin-right: 10px;
    }
  }
  .table-container {
    position: relative;
    height: calc(100% - 58px);
  }
  .edit-item {
    display: flex;
    justify-content: space-between;
    .el-form-item {
      width: 48%;
    }
  }
  .check-groups {
    display: flex;
    justify-content: space-around;
    width: 40%;
  }
  .options {
    display: flex;
    .el-form-item {
      margin-right: 10px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style>
